﻿@{
    ViewBag.Title = "AuthorizationIndex";
}
@model List<CRM.Admin.Contracts.Dto.Sys.RoleDto>
@section head
{
    <link href="@Url.Content("~/ScriptPlugin/easyui/themes/gray/easyui.css")" rel="stylesheet" />
    <link href="@Url.Content("~/ScriptPlugin/easyui/themes/icon.css")" rel="stylesheet" />
    <script type="text/javascript" src="@Url.Content("~/ScriptPlugin/easyui/jquery.easyui.min.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/ScriptPlugin/easyui/locale/easyui-lang-zh_CN.js")"></script>
    <style type="text/css">
        .tree-icon {
            display: none;
        }
        .authaction
        {
            display:inline-block;
            margin-right:3px;
        }
        .datagrid-row input
        {
            margin-right:1px;
            width:14px;height:14px;
            cursor:pointer;
        }
        .rolelist{
            display:inline-block;width:100%;background-position:left center;padding-left:18px;
        }

    </style>
}
<div style="float:left;width:190px;height:100%">
    <div class="content-bar-color" style="height: 34px; line-height: 34px; text-align: center">
        角色列表
    </div>
    <ul class="content-list">
        @{
            foreach (var item in Model)
            {
                <li data-node-id="@item.Id"><span class="rolelist p-icon-role">@item.Name</span></li>
            }
        }
    </ul>
</div>
<div style="position:absolute;left:190px;right:0;top:0px;height:100%">
    <div id="grid" style="height:99%">
        <div id="toolpannel">
            <div class="content-pannel-buttons">
                <a><b class="p-icon-reload">刷新 </b></a><a onclick="AuthorizationInsertOrUpdate()">
                    <b class="p-icon-save">保存</b>
                </a>
                <div style="float:right;padding-right:20px;color:red">注：功能权限为模块所有子页面的权限，勾选则相应具备相应按钮权限，否则按钮不出现</div>
            </div>
        </div>
    </div>
</div>
@section foot
{
<script type="text/javascript">
    $.extend($.fn.treegrid.defaults.view, {
        onAfterRender: function (target) {
            target = $(target);
            var opts = $(target).treegrid("options");
            if (!opts.usercheck) {
                return;
            }
            var panel = $(target).treegrid("getPanel");
            var gridBody = panel.find("div.datagrid-body");
            var idField = opts.idField;
            var doms = "";
            if (typeof (opts.usercheck) == "string") {
                doms = opts.usercheck;
            }
            else {
                for (var i = 0; i < opts.usercheck.length; i++) {
                    if (opts.usercheck[i] == "") {
                        return;
                    }
                    if (doms != "") {
                        doms += ",";
                    }
                    doms += ".datagrid-cell input[type=checkbox][name='" + opts.usercheck[i] + "']";
                }
            }
            gridBody.find(doms).unbind(".treegrid").click(function (e) {
                var id = $(this).parents(".datagrid-row").attr("node-id");
                var status = false;
                if ($(this).prop("checked")) status = true;
                selectParent(target, id, idField, status);
                selectChildren(target, id, idField, true, status);
                //if (status) {
                //    target.treegrid('checkRow', id);
                //}
                //else {
                //    target.treegrid('uncheckRow', id);
                //}
                if (opts.onuserchecked) {
                    opts.onuserchecked(status, id);
                }
                function selectParent(target, id, idField, status) {
                    var parent = target.treegrid('getParent', id);
                    if (parent) {
                        var parentId = parent[idField];

                        if (status) {
                            $("[node-id='" + parentId + "']").find(doms).prop("checked", true);
                            //target.treegrid('checkRow', parentId);
                        }
                        //if (opts.onuserchecked) {
                        //    opts.onuserchecked(status, parentId);
                        //}
                        selectParent(target, parentId, idField, status);
                    }
                }
                function selectChildren(target, id, idField, deepCascade, status) {
                    if (status && deepCascade)
                        target.treegrid('expand', id);
                    var children = target.treegrid('getChildren', id);
                    for (var i = 0; i < children.length; i++) {
                        var childId = children[i][idField];
                        if (status) {
                            $("[node-id='" + childId + "']").find(doms).prop("checked", true);
                            //target.treegrid('checkRow', childId);
                        }

                        else {
                            $("[node-id='" + childId + "']").find(doms).prop("checked", false);
                            //target.treegrid('uncheckRow', childId);
                        }
                        if (opts.onuserchecked) {
                            opts.onuserchecked(status, childId);
                        }
                        selectChildren(target, childId, idField, deepCascade, status);
                    }
                }
                e.stopPropagation();
            });
        }
    });
</script>  
<script type="text/javascript">
    var grid;
    function LoadGridData()
    {
        grid = $("#grid").treegrid({
            url: "@Url.Content("~/Sys/Authorization/GetAllMenuGridData")",
            idField: 'Id',
            treeField: 'Name',
            animate: false,
            rownumbers: true,
            toolbar: "#toolpannel",
            checkbox: true,
            singleSelect: true,
            loadMsg: "菜单数据加载中......请稍候",
            usercheck: ["auth"],
            checkOnSelect:false,
            onuserchecked:checkedOne,
            title: "@Html.GetGridTitle("系统管理","角色权限设置")",
            columns: [[
                {
                    field: 'Name', title: '菜单名称', width: 170, formatter: function (val, row, index) {
                        return " <input type=\"checkbox\" name=\"auth\" value=\"" + row.Id + "\" /> " + val;
                    }
                },
                
                {
                    field: 'ActionPath', title: '功能选项',formatter: function (val, row, index) {
                        if (val == null)
                        {
                            return "";
                        }
                        var returndom = "";
                        var actionitem = row.ActionPath.split(',');
                        for(var i=0;i<actionitem.length;i++)
                        {
                            if(actionitem[i]!="")
                            {
                                returndom=returndom+ "<span>"+getactionNode(actionitem[i])+"</span>";
                            }
                        }
                        return returndom;
                    }
                },
               { field: 'Description', title: '菜单描述' }
            ]]
        });
    }
    function getactionNode(code)
    {
        var val = "";
        switch(code)
        {
            case "insert":
                val = "<span class=\"authaction\"><input type=\"checkbox\" checked=\"true\" name=\"insert\" />新增</span>";
                break;
            case "update":
                val = "<span class=\"authaction\"><input type=\"checkbox\" checked=\"true\" name=\"update\" />编辑</span>";
                break;
            case "delete":
                val = "<span class=\"authaction\"><input type=\"checkbox\" checked=\"true\" name=\"delete\" />删除</span>";
                break;
            case "detail":
                val = "<span class=\"authaction\"><input type=\"checkbox\" checked=\"true\" name=\"detail\" />客户分析</span>";
                break;
        }
        return val;
    }
    function checkedOne(state,id)
    {
        if (state)
        {
            $("[node-id='" + id + "'] input[type=checkbox]").prop("checked", true);
        }
        else
        {
            $("[node-id='" + id + "'] input[type=checkbox]").prop("checked", false);
        }
    }
    LoadGridData();

    $(".content-list li").click(function () {
        $(".content-list .selected").removeClass("selected");
        $(this).addClass("selected");
        var nodeid = $(this).attr("data-node-id");
        K.AjaxJson("@Url.Content("~/Sys/Authorization/GetRoleAuthorization")", { RoleId: nodeid }, function (data) {
            var target = $("#grid");
            var doms = $(".datagrid-cell input[type=checkbox][name='auth']");
            target.treegrid('unselectAll');
            $(".datagrid-cell input[type=checkbox]").prop("checked", false);
            for(var i=0;i<data.length;i++)
            {
                var mid = data[i].MenuNodeId;
                $("[node-id='" + mid + "']").find(doms).prop("checked", true);
                if (data[i].ActionCodes != "")
                {
                    var codes = data[i].ActionCodes.split(',');
                    for(var j=0;j<codes.length;j++)
                    {
                        $("[node-id='" + data[i].MenuNodeId + "']").find("input[type=checkbox][name='" + codes[j] + "']").prop("checked", true);
                    }
                }
               
                target.treegrid('checkRow', mid);
            }
        }, "权限加载中...");
    });

    function AuthorizationInsertOrUpdate()
    {
        var RoleId = $(".content-list .selected").attr("data-node-id");

        if (RoleId == undefined) {
            K.Alert("请选择需要授权的角色");
            return false;
        }
        var RoleName=$(".content-list .selected .rolelist").text();
        var viewdto = { RoleId: RoleId, RoleName: RoleName, AuthDtos: [] };

        var selectedNode = $("#grid").treegrid("getData");
        function getChilden(childennodes)
        {
            for (var i = 0; i < childennodes.length; i++) {
                if (childennodes[i].ActionNode == 2) {
                    var doms = $(".datagrid-cell input[type=checkbox][name='auth']:checked");
                    var ischeked = $("[node-id='" + childennodes[i].Id + "']").find(doms).size();
                    if (ischeked == 1)
                    {
                        var node = { MenuNodeId: childennodes[i].Id, RoleId: RoleId, ActionCodes: "" };
                        var acodes = "";
                        $("[node-id='" + childennodes[i].Id + "'] input[type=checkbox]:checked").each(function () {
                            var dname = $(this).prop("name");
                            if (dname != "auth") {
                                if (acodes != "") {
                                    acodes = acodes + ",";
                                }
                                acodes = acodes + dname;
                            }
                        });
                        node.ActionCodes = acodes;
                        viewdto.AuthDtos.push(node);
                    }
                }
                else
                {
                    if (childennodes[i].children != null)
                    {
                        getChilden(childennodes[i].children);
                    }
                }
            }
        }
        getChilden(selectedNode);
        K.AjaxJson("@Url.Content("~/Sys/Authorization/InsertOrUpdateAuthorization")", { authtempdto: JSON.stringify(viewdto) }, function (result) {
            K.ShowOrAlert(result);
        }, "权限保存中...");
    }
</script>  
}